package secret.hehe.com.secret.Activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import secret.hehe.com.secret.R;
import secret.hehe.com.secret.Util.Util;

/**
 * Created by DELL on 2018/4/26.
 */

public class PictureActivity extends AppCompatActivity {

    private ImageView picture;
    private TextView hiddenText;
    private String userId;
    private String eid;
    private String path;
    private AlertDialog loading;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture);

        Intent intent = getIntent();
        try{
            userId=(String) intent.getSerializableExtra("userId");
            eid=(String) intent.getSerializableExtra("eid");
            path=(String) intent.getSerializableExtra("path");
        }catch (Exception e){
            e.printStackTrace();
        }
        //防止杀死变量
        if (savedInstanceState != null) {
            try {
                userId = savedInstanceState.getString("userId");
                eid = savedInstanceState.getString("eid");
                path = savedInstanceState.getString("path");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        picture = (ImageView) findViewById(R.id.show_picture);
        hiddenText = (TextView) findViewById(R.id.picture_hidden_text);
        hiddenText.setVisibility(TextView.INVISIBLE);

        //Android6.0后读写sd卡权限需要动态申请
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    2000);
        }else{
            Util util = new Util();
            Util.downloadFileThread downloadFileThread = util.new downloadFileThread(userId,path,handler,1);
            downloadFileThread.start();
        }

        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_picture, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
            case R.id.picture_hidden_text_show:{
                final EditText et = new EditText(this);
                et.setInputType(InputType.TYPE_CLASS_NUMBER);
                InputFilter[] filters = {new InputFilter.LengthFilter(4)};
                et.setFilters(filters);
                new AlertDialog.Builder(this).setTitle("输入密码")
                        .setView(et)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                String params = "eid=" + eid
                                        +"&&keybody=" +et.getText().toString();
                                Util util = new Util();
                                Util.postThread pwdThread = util.new postThread("/email/checkkeybody",getApplicationContext(),params,handler,3);
                                pwdThread.start();
                                loading = new AlertDialog.Builder(PictureActivity.this).setTitle("提示")//设置对话框标题
                                        .setMessage("确认中")//设置显示的内容
                                        .setCancelable(false)
                                        .show();
                                return;
                            }
                        }).setNegativeButton("取消", null).show();
            }

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //保存变量
        super.onSaveInstanceState(outState);
        outState.putString("userId", userId);
        outState.putString("eid", eid);
        outState.putString("path", path);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 2000) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Util util = new Util();
                Util.downloadFileThread downloadFileThread = util.new downloadFileThread(userId,path,handler,1);
                downloadFileThread.start();
            } else {
                // Permission Denied
                Toast.makeText(PictureActivity.this, "无法保存图片，请获取权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //相应接受数据
            if (msg.what == 1) {
                String name = path.substring(path.lastIndexOf("/"));
                StringBuilder stringBuilder = new StringBuilder().append(Environment.getExternalStorageDirectory())
                        .append("/secret/")
                        .append(userId)
                        .append("/pic")
                        .append(name);
                Bitmap bm = BitmapFactory.decodeFile(stringBuilder.toString());
                picture.setImageBitmap(bm);
            }
            if (msg.what == 2){
                Toast.makeText(PictureActivity.this, "图片保存成功", Toast.LENGTH_SHORT).show();
                handler.sendEmptyMessage(1);
            }
            if (msg.what == 3) {
                //确认邮件密码
                try{
                    if(loading!=null){
                        loading.dismiss();
                        loading=null;
                    }
                    JSONObject jsonObject = new JSONObject(msg.obj.toString());
                    int code = jsonObject.getInt("code");
                    if(code==200){
                        //密码正确
                        Toast.makeText(PictureActivity.this, "密码正确", Toast.LENGTH_SHORT).show();
                        //获取文件名及后缀
                        String name = path.substring(path.lastIndexOf("/"));
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.append(Environment.getExternalStorageDirectory())
                                .append("/secret/")
                                .append(userId)
                                .append("/pic")
                                .append(name);
                        File file=new File(stringBuilder.toString());
                        InputStreamReader reader = new InputStreamReader(new FileInputStream(file)); // 建立一个输入流对象reader
                        BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
                        String lineTxt = null;
                        StringBuilder result = new StringBuilder();
                        String hidden;
                        while ((lineTxt = br.readLine()) != null) {
                            result.append(lineTxt);
                        }
                        br.close();
                        hidden = result.toString();
                        int first = hidden.lastIndexOf("[{"),last = hidden.lastIndexOf("}]");
                        if(first<0||last<0){
                            Toast.makeText(PictureActivity.this, "无隐藏信息", Toast.LENGTH_SHORT).show();
                            return;
                        }else{
                            hidden = hidden.substring(first+2,last);
                            hiddenText.setText(hidden);
                            hiddenText.setVisibility(View.VISIBLE);
                            picture.setVisibility(View.INVISIBLE);
                        }

                    }else{
                        //密码错误
                        if(loading!=null){
                            loading.dismiss();
                            loading=null;
                        }
                        Toast.makeText(PictureActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (msg.what == 0) {
                if(loading!=null){
                    loading.dismiss();
                    loading=null;
                }
                Toast.makeText(PictureActivity.this, "无网络或访问服务器出错", Toast.LENGTH_SHORT).show();
            }
        }
    };
}
